/*
*Copyright 2021-2023 NERCIS
*
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/

package cn.ac.nercis.pes.community.controller.evaluation.prepare;

import cn.ac.nercis.pes.common.constant.evaluation.EvaluationModule;
import cn.ac.nercis.pes.common.constant.project.FinishState;
import cn.ac.nercis.pes.common.utils.JsonUtils;
import cn.ac.nercis.pes.community.component.controls.CustomScrollPane;
import cn.ac.nercis.pes.community.component.controls.MenuListCell;
import cn.ac.nercis.pes.community.component.controls.PesBasisOption;
import cn.ac.nercis.pes.community.component.dialog.*;
import cn.ac.nercis.pes.community.controller.base.GlobalEventHandle;
import cn.ac.nercis.pes.community.controller.base.InitEvalDataLoad;
import cn.ac.nercis.pes.community.model.vo.MenuVO;
import cn.ac.nercis.pes.community.utils.*;
import cn.ac.nercis.pes.community.views.evaluation.prepare.PrepareView;
import cn.ac.nercis.pes.model.dto.evaluation.content.EvaluationBasisDTO;
import cn.ac.nercis.pes.model.dto.evaluation.content.EvaluationBasisOptionDTO;
import cn.ac.nercis.pes.service.evaluation.EvaluationContentService;
import javafx.application.Platform;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.net.URL;
import java.util.List;
import java.util.Objects;
import java.util.ResourceBundle;
import java.util.concurrent.CompletableFuture;

/**
 * 测评依据管理控制器
 * @author zpy
 * @version 1.0.0
 */
@Slf4j
public class EvaluationBasisController implements Initializable, GlobalEventHandle, InitEvalDataLoad {

    @FXML
    private StackPane page;
    @FXML
    private Button saveButton;
    @FXML
    private Button tmpSaveButton;

    @FXML
    private ListView<MenuVO> menuList;
    @FXML
    private CustomScrollPane basisStandardBox;
    @FXML
    private CustomScrollPane refStandardBox;
    @FXML
    private VBox basisOptionBox;
    @FXML
    private VBox refOptionBox;
    @FXML
    private Button addBasisStandardBtn;
    @FXML
    private Button addRefStandardBtn;

    private final EvaluationContentService evaluationContentService;
    protected final SimpleBooleanProperty dataSaving = new SimpleBooleanProperty(false);
    private String currentSystemId;

    public EvaluationBasisController() {
        this.evaluationContentService = SpringUtils.getBean(EvaluationContentService.class);
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        saveButton.setGraphic(IconUtils.getGlyph("save-button-icon","btn-icon"));
        tmpSaveButton.setGraphic(IconUtils.getGlyph("temp-save-button-icon","btn-icon"));
        saveButton.disableProperty().bind(dataSaving);
        tmpSaveButton.disableProperty().bind(dataSaving);
        addBasisStandardBtn.setGraphic(IconUtils.getGlyph("add-picture-icon", "add-basis-option-icon"));
        addRefStandardBtn.setGraphic(IconUtils.getGlyph("add-picture-icon", "add-basis-option-icon"));
        initializeMenu();
        addBasisStandardBtn.setAlignment(Pos.TOP_CENTER);
        addBasisStandardBtn.setOnAction((actionEvent -> addOption(basisOptionBox)));
        addRefStandardBtn.setOnAction((actionEvent -> addOption(refOptionBox)));
        GuiStore.applyQuickSave(this.page,this::onGlobalSave);
    }

    @Override
    public void initializeData(String systemId){
        LogUtils.info(log, "初始化测评依据内容...");
        this.currentSystemId = systemId;
        this.loadEvaluationBasis();
        this.menuList.getSelectionModel().select(0);
    }

    @Override
    public void onGlobalSave() {
        LogUtils.info(log, "执行快捷保存操作...");
        saveContent(false);
    }

    @FXML
    public void onTmpSave(){
        LogUtils.info(log, "执行暂存操作...");
        saveContent(false);
    }

    @FXML
    public void onFinishSave(){
        LogUtils.info(log, "执行保存操作...");
        saveContent(true);
    }

    private void loadEvaluationBasis() {
        LogUtils.info(log, "获取测评依据信息...");
        LogUtils.info(log, "请求数据：{}", this.currentSystemId);
        CompletableFuture.supplyAsync(() -> this.evaluationContentService.findEvaluationBasis(this.currentSystemId))
                .thenAccept(res -> Platform.runLater(() -> {
                    this.loadOptions(basisOptionBox,res.getBasisStandard());
                    this.loadOptions(refOptionBox,res.getRefStandard());
                }))
                .exceptionally((ex) -> {
                    log.error("获取测评依据信息出错!", ex);
                    return null;
                });
    }

    private void loadOptions(VBox optionBox,List<EvaluationBasisOptionDTO> basisStandard){
        //清空旧的内容
        optionBox.getChildren().clear();
        basisStandard.forEach(bs->{
            var option = new PesBasisOption();
            option.setSelected(bs.getSelected());
            option.setIsAdd(false);
            option.setText(bs.getName());
            option.setOnModifyEvent(this::onModifyOption);
            option.setOnDeleteEvent(this::onDeleteOption);
            optionBox.getChildren().add(option);
        });
    }

    protected void onModifyOption(PesBasisOption source) {
        realTimeSave();
    }

    private void realTimeSave(){
        LogUtils.info(log, "实时保存测评依据信息...");
        var data = collectData();
        this.dataSaving.setValue(true);
        CompletableFuture.supplyAsync(() -> this.evaluationContentService.saveEvaluationBasis(this.currentSystemId,data))
                .thenAccept(res -> Platform.runLater(() -> {
                    this.dataSaving.setValue(false);
                    if (!res.isSuccess()) {
                        log.warn("实时保存测评依据信息失败!");
                        LogUtils.record(log, "请求数据，systemId：{}，data：{}",this.currentSystemId, JsonUtils.toJson(data));
                        MessageDialog.builder()
                                .withContainer(this.page)
                                .withType(MessageType.FAIL)
                                .withMessage("实时保存测评依据信息失败")
                                .build().show();
                    }else{
                        refreshFinishProcess(false);
                    }
                }))
                .exceptionally((ex) -> {
                    this.dataSaving.setValue(false);
                    log.error("实时保存测评依据信息出错!", ex);
                    LogUtils.record(log, "请求数据，systemId：{}，data：{}",this.currentSystemId, JsonUtils.toJson(data));
                    return null;
                });
    }

    private void saveContent(boolean finish){
        if(hasEmpty(basisOptionBox)){
            MessageDialog.builder()
                    .withContainer(this.page)
                    .withType(MessageType.FAIL)
                    .withMessage("存在无内容的依据标准和规范")
                    .build().show();
            return;
        }
        if(hasEmpty(refOptionBox)){
            MessageDialog.builder()
                    .withContainer(this.page)
                    .withType(MessageType.FAIL)
                    .withMessage("存在无内容的参考标准和规范")
                    .build().show();
            return;
        }
        var data = collectData();
        LogUtils.info(log, "保存测评依据信息...");
        LogUtils.record(log, "请求数据，systemId：{}，data：{}",this.currentSystemId, JsonUtils.toJson(data));
        this.dataSaving.setValue(true);
        CompletableFuture.supplyAsync(() -> this.evaluationContentService.saveEvaluationBasis(this.currentSystemId,data))
                .thenAccept(res -> Platform.runLater(() -> {
                    this.dataSaving.setValue(false);
                    if (res.isSuccess()) {
                        this.refreshFinishProcess(finish);
                        MessageDialog.builder()
                                .withContainer(this.page)
                                .withType(MessageType.SUCCESS)
                                .withMessage("保存成功")
                                .build().show();
                    }else{
                        MessageDialog.builder()
                                .withContainer(this.page)
                                .withType(MessageType.FAIL)
                                .withMessage(res.getMsg())
                                .build().show();
                    }
                }))
                .exceptionally((ex) -> {
                    this.dataSaving.setValue(false);
                    log.error("保存测评依据信息出错!", ex);
                    return null;
                });
    }

    private boolean hasEmpty(VBox optionBox){
        return optionBox.getChildren()
                .stream()
                .map(n->{
                    if(n instanceof PesBasisOption option && StringUtils.isNotBlank(option.getText())){
                        return EvaluationBasisOptionDTO.builder()
                                .selected(option.getSelected())
                                .name(option.getText())
                                .build();
                    }else{
                        return null;
                    }
                })
                .anyMatch(Objects::isNull);
    }

    private long validOptionCount(VBox optionBox){
        return optionBox.getChildren()
                .stream()
                .map(n->{
                    if(n instanceof PesBasisOption option && StringUtils.isNotBlank(option.getText())){
                        return EvaluationBasisOptionDTO.builder()
                                .selected(option.getSelected())
                                .name(option.getText())
                                .build();
                    }else{
                        return null;
                    }
                })
                .filter(option->Objects.nonNull(option) && option.getSelected())
                .count();
    }

    private EvaluationBasisDTO collectData(){
        return EvaluationBasisDTO.builder()
                .basisStandard(collectData(basisOptionBox))
                .refStandard(collectData(refOptionBox))
                .build();
    }

    private List<EvaluationBasisOptionDTO> collectData(VBox optionBox){
        return optionBox.getChildren()
                .stream()
                .map(n->{
                    if(n instanceof PesBasisOption option && StringUtils.isNotBlank(option.getText())){
                        return EvaluationBasisOptionDTO.builder()
                                .selected(option.getSelected())
                                .name(option.getText())
                                .build();
                    }else{
                        return null;
                    }
                })
                .filter(Objects::nonNull)
                .toList();
    }

    private void refreshFinishProcess(boolean finish){
        var prepareView = AppStore.getEvaluationView(this.currentSystemId, PrepareView.class);
        if(prepareView.getController() instanceof PrepareController controller){
            controller.setEvalProcess(EvaluationModule.EVALUATION_BASIS, finish ? FinishState.FINISH:FinishState.INCOMPLETE);
        }
    }

    protected void onDeleteOption(PesBasisOption source) {
        LogUtils.info(log, "执行删除操作...");
        if(source.getIsAdd()){
            basisOptionBox.getChildren().remove(source);
            refOptionBox.getChildren().remove(source);
            return;
        }
        AlertDialog alertDialog = AlertDialog.builder()
                .withMode(AlertMode.CONFIRM)
                .withType(AlertType.WARN)
                .withTitle("删除提示")
                .withContent("确认删除当前信息吗？")
                .withContainer(this.page)
                .build();
        alertDialog.show((confirm)->{
            if(!confirm){
                return;
            }
            basisOptionBox.getChildren().remove(source);
            refOptionBox.getChildren().remove(source);
            realTimeSave();
        });
    }

    private void addOption(VBox optionBox){
        var option = new PesBasisOption();
        option.setSelected(false);
        option.setIsAdd(true);
        option.setOnModifyEvent(this::onModifyOption);
        option.setOnDeleteEvent(this::onDeleteOption);
        optionBox.getChildren().add(option);
    }

    private void initializeMenu(){
        this.menuList.setCellFactory(cf->new MenuListCell());
        this.menuList.getSelectionModel()
                .selectedItemProperty()
                .addListener((observable, oldValue, newValue) -> {
                    if(Objects.nonNull(newValue)){
                        loadContent(newValue);
                    }
                });
        this.menuList.getItems().add(new MenuVO(1,"basisStandard","依据标准和规范",""));
        this.menuList.getItems().add(new MenuVO(2,"refStandard","参考标准和规范",""));
    }

    private void loadContent(MenuVO menu){
        if(StringUtils.equals(menu.getCode(),"basisStandard")){
            this.refStandardBox.setVisible(false);
            this.basisStandardBox.setVisible(true);
        } else{
            this.basisStandardBox.setVisible(false);
            this.refStandardBox.setVisible(true);
        }
    }

}